<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Models\Manage;
use App\Models\PictureLiveAppointUser;
use App\Models\PictureLiveWorks;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 图片直播管理
 */
class PictureLiveController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\PictureLive();
        $this->validate = new  \App\Validate\PictureLiveValidate();
    }

    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param is_play string 是否发布   1 已发布  2 未发布
     * @param keywords string 搜索关键词
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $create_start_time = $this->request->create_start_time;
        $create_end_time = $this->request->create_end_time;
        $is_play = $this->request->is_play;

        $res = $this->model->lists(null, $keywords, $is_play, $start_time, $end_time, $create_start_time, $create_end_time, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
            $res['data'][$key]['status'] = $this->model->getPictureLiveStatus($val);
            //  $res['data'][$key]['manage_name'] = Manage::getManageNameByManageId($val['manage_id']);

            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 活动id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        if ($res['is_appoint'] == 1) {
            //获取指定用户信息
            $pictureLiveAppointUserModel = new PictureLiveAppointUser();
            $appoint_user_info = $pictureLiveAppointUserModel->getAppointUserInfo($res->id, null, 999);
            $res->appoint_user_info = $appoint_user_info['data'];
        } else {
            $res->appoint_user_info = [];
        }

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param title string 活动名称
     * @param img string 活动封面
     * @param main_img int 进入主界面封面图片
     * @param host_handle int 主办单位
     * @param tel int 咨询电话
     * @param address int 地址
     * @param con_start_time int 投稿开始时间
     * @param con_end_time string  投稿结束时间
     * @param vote_start_time int 点赞开始时间
     * @param vote_end_time int 点赞结束时间
     * @param is_check int 前台上传照片是否需要审核   1.是   2.否(默认）
     * @param vote_way int 点赞方式   1  总点赞方式   2 每日点赞方式  3 无需点赞
     * @param number int 点赞数
     * @param uploads_number int 每个人上传限制张数，后台上传不影响   0 不限制   总的最多500张  必传
     * @param uploads_way int 上传方式  1 前台后台都可以上传   2  仅支持后台上传  3 仅支持前台上传
     * @param is_appoint 是否指定用户上传  1 指定  2 不指定（都可以上传）  只能指定用户上传
     * @param appoint_user_id 指定用户id 多个 逗号拼接   不能超过 3个用户
     * @param intro int 简介

     * @param watermark_type int 水印类型   0 无水印 1、默认图片水印 2 自定义图片水印  3 自定义文字水印
     * @param watermark_img int 水印图片
     * @param watermark_text int 水印文字  水印文字，不能超过30个字符
     * @param share_title string 分享标题
     * @param share_img string 分享图片

     * @param theme_color int 主题颜色
     * @param animation int 动画  单选框
     * @param animation_time int 动画显示时间
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (mb_strlen($this->request->address) > 45) {
            return $this->returnApi(202, "地址最多45个字！");
        }
        if ($this->request->uploads_number > 500) {
            return $this->returnApi(202, "上传张数最多500张！");
        }

        if ($this->request->watermark_type == 2 && empty($this->request->watermark_img)) {
            return $this->returnApi(202, "请上传水印图片");
        }
        if ($this->request->watermark_type == 3) {
            if (empty($this->request->watermark_text)) {
                return $this->returnApi(202, "请填写水印文字");
            }
            if (strlen($this->request->watermark_text) > 30) {
                return $this->returnApi(202, "水印文字不能超过30个字符");
            }
        }
        if (!empty($this->request->share_title) && mb_strlen($this->request->share_title) > 12) {
            return $this->returnApi(202, "分享标题文字不能超过12个字");
        }
        if ($this->request->vote_way != 3 && empty($this->request->number)) {
            return $this->returnApi(202, "请填写点赞数");
        }
        if ($this->request->vote_way != 3 && (empty($this->request->vote_start_time) || empty($this->request->vote_end_time))) {
            return $this->returnApi(201, "点赞时间不能为空");
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title');
        if ($is_exists) {
            return $this->returnApi(202, "该直播名称已存在");
        }

        //生成二维码
        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('picture_live');
        if ($qr_code === false) {
            Log::error("图片直播二维码生成失败,请手动生成");
            return $this->returnApi(202, "二维码生成失败");
        }
        $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pMob/home/index?from=readshare_activity&token=' . $qr_code; //直播活动二维码的链接  扫码跳转直播活动二维码
        $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1, [0, 0, 0], 'L'); //减小容错，让二维码更简单

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'title' => $this->request->title,
                'main_img' => $this->request->main_img ? $this->request->main_img : 'default/default_picture_live_main_img.png',
                'img' => $this->request->img ? $this->request->img : 'default/default_picture_live_img.png',
                'host_handle' => $this->request->host_handle,
                'tel' => $this->request->tel,
                'address' => $this->request->address,
                'con_start_time' => $this->request->con_start_time,
                'con_end_time' => $this->request->con_end_time,
                'vote_start_time' => $this->request->vote_start_time,
                'vote_end_time' => $this->request->vote_end_time,
                'is_check' => $this->request->is_check,
                'vote_way' => $this->request->vote_way,
                'number' => $this->request->vote_way == 3 ? 0 : $this->request->number,
                'uploads_number' => $this->request->uploads_number ? $this->request->uploads_number : 0,
                'uploads_way' => $this->request->uploads_way,
                //  'is_appoint' => $this->request->is_appoint,
                'is_appoint' => 1,
                'intro' => $this->request->intro,
                'is_play' => $this->request->is_play,

                'watermark_type' => empty($this->request->watermark_type) ? 0 : $this->request->watermark_type,
                'watermark_img' => $this->request->watermark_type == 2 ? $this->request->watermark_img : ($this->request->watermark_type == 1 ? 'default/default_watermark_img.png' : null),
                'watermark_text' => $this->request->watermark_type == 3 ? $this->request->watermark_text : null,
                'share_title' => $this->request->share_title,
                'share_img' => $this->request->share_img,

                'theme_color' => $this->request->theme_color,
                'animation' => $this->request->animation,
                'animation_time' => $this->request->animation_time,
                'qr_code' => $qr_code,
                'qr_url' => $qr_url,
                'manage_id' => $this->request->manage_id
            ];
            $this->model->add($data);
            //处理指定用户上传
            if ($this->request->is_appoint == 1) {
                if ($this->request->appoint_user_id) {
                    $appoint_user_id = array_unique(array_filter(explode(',', $this->request->appoint_user_id)));
                    if (count($appoint_user_id) > 3) {
                        throw new Exception("最多只能指定3个用户");
                    }
                    $pictureLiveAppointUserModel = new PictureLiveAppointUser();
                    $pictureLiveAppointUserModel->interTableChange('act_id', $this->model->id, 'user_id', $this->request->appoint_user_id, 'add');
                }
            }
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }



    /**
     * 修改
     * @param id string 活动id
     * @param title string 活动名称
     * @param img string 活动封面
     * @param main_img int 进入主界面封面图片
     * @param host_handle int 主办单位
     * @param tel int 咨询方式
     * @param address int 地址
     * @param con_start_time int 投稿开始时间
     * @param con_end_time string  投稿结束时间
     * @param vote_start_time int 点赞开始时间
     * @param vote_end_time int 点赞结束时间
     * @param is_check int 前台上传照片是否需要审核   1.是   2.否(默认）
     * @param vote_way int 点赞方式   1  总点赞方式   2 每日点赞方式
     * @param number int 点赞数
     * @param uploads_number int 每个人上传限制张数，后台上传不影响   0 不限制  总的最多500张  必传
     * @param uploads_way int 上传方式  1 前台后台都可以上传   2  仅支持后台上传  3 仅支持前台上传
     * @param is_appoint 是否指定用户上传  1 指定  2 不指定（都可以上传） 只能指定用户上传
     * @param appoint_user_id 指定用户id 多个 逗号拼接  只能指定 3个用户
     * @param intro int 简介


     * @param watermark_type int 水印类型   0 无水印 1、默认图片水印 2 自定义图片水印  3 自定义文字水印
     * @param watermark_img int 水印图片
     * @param watermark_text int 水印文字  水印文字，不能超过30个字符
     * @param share_title string 分享标题
     * @param share_img string 分享图片
     *
     * @param theme_color int 主题颜色
     * @param animation int 动画  单选框
     * @param animation_time int 动画显示时间
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (mb_strlen($this->request->address) > 45) {
            return $this->returnApi(201, "地址最多45个字！");
        }
        if ($this->request->uploads_number > 500) {
            return $this->returnApi(201, "上传张数最多500张！");
        }
        if ($this->request->watermark_type == 2 && empty($this->request->watermark_img)) {
            return $this->returnApi(201, "请上传水印图片");
        }
        if ($this->request->watermark_type == 3) {
            if (empty($this->request->watermark_text)) {
                return $this->returnApi(201, "请填写水印文字");
            }
            if (strlen($this->request->watermark_text) > 30) {
                return $this->returnApi(201, "水印文字不能超过30个字符");
            }
        }
        if (!empty($this->request->share_title) && mb_strlen($this->request->share_title) > 12) {
            return $this->returnApi(201, "分享标题文字不能超过12个字");
        }
        if ($this->request->vote_way != 3 && empty($this->request->number)) {
            return $this->returnApi(201, "请填写点赞数");
        }
        if ($this->request->vote_way != 3 && (empty($this->request->vote_start_time) || empty($this->request->vote_end_time))) {
            return $this->returnApi(201, "点赞时间不能为空");
        }
        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        if ($res->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该直播名称已存在");
        }
        $old_img = $res->img;
        $old_main_img = $res->main_img;
        $old_watermark_img = $res->watermark_img;

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'id' => $this->request->id,
                'title' => $this->request->title,
                'main_img' => $this->request->main_img ? $this->request->main_img : 'default/default_picture_live_main_img.png',
                'img' => $this->request->img ? $this->request->img : 'default/default_picture_live_img.png',
                'host_handle' => $this->request->host_handle,
                'tel' => $this->request->tel,
                'address' => $this->request->address,
                'con_start_time' => $this->request->con_start_time,
                'con_end_time' => $this->request->con_end_time,
                'vote_start_time' => $this->request->vote_start_time,
                'vote_end_time' => $this->request->vote_end_time,
                'is_check' => $this->request->is_check,
                'vote_way' => $this->request->vote_way,
                'number' => $this->request->vote_way == 3 ? 0 : $this->request->number,
                'uploads_number' => $this->request->uploads_number ? $this->request->uploads_number : 0,
                'uploads_way' => $this->request->uploads_way,
                //   'is_appoint' => $this->request->is_appoint,
                'is_appoint' => 1,
                'intro' => $this->request->intro,
                'is_play' => $this->request->is_play,

                'watermark_type' => empty($this->request->watermark_type) ? 0 : $this->request->watermark_type,
                'watermark_img' => $this->request->watermark_type == 2 ? $this->request->watermark_img : ($this->request->watermark_type == 1 ? 'default/default_watermark_img.png' : null),
                'watermark_text' => $this->request->watermark_type == 3 ? $this->request->watermark_text : null,
                'share_title' => $this->request->share_title,
                'share_img' => $this->request->share_img,

                'theme_color' => $this->request->theme_color,
                'animation' => $this->request->animation,
                'animation_time' => $this->request->animation_time,
            ];
            if (empty($res['qr_url'])) {
                //生成二维码
                $qrCodeObj = new QrCodeController();
                if (empty($res['qr_code'])) {
                    $qr_code = $qrCodeObj->getQrCode('picture_live');
                    if ($qr_code === false) {
                        Log::error("图片直播二维码生成失败,请手动生成");
                        throw new Exception("二维码生成失败");
                    }
                } else {
                    $qr_code = $res['qr_code'];
                }
                $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pMob/home/index?from=readshare_activity&token=' . $qr_code; //直播活动二维码的链接  扫码跳转直播活动二维码
                $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1, [0, 0, 0], 'L'); //减小容错，让二维码更简单
                $data['qr_url'] = $qr_url;
                $data['qr_code'] = $qr_code;
            }

            $this->model->change($data);

            //处理指定用户上传
            if ($this->request->is_appoint == 1) {
                if ($this->request->appoint_user_id) {
                    $appoint_user_id = array_unique(array_filter(explode(',', $this->request->appoint_user_id)));
                    if (count($appoint_user_id) > 3) {
                        throw new Exception("最多只能指定3个用户");
                    }
                    $pictureLiveAppointUserModel = new PictureLiveAppointUser();
                    $pictureLiveAppointUserModel->interTableChange('act_id', $this->request->id, 'user_id',  $this->request->appoint_user_id, 'change');
                }
            }

            //删除旧资源
            if ($old_img != $this->request->img && $old_img != 'default/default_picture_live_img.png') {
                $this->deleteFile($old_img);
            }
            if ($old_main_img != $this->request->main_img && $old_main_img != 'default/default_picture_live_main_img.png') {
                $this->deleteFile($old_main_img);
            }
            if (!empty($old_watermark_img) && $old_watermark_img != $this->request->watermark_img && $old_watermark_img != 'default/default_watermark_img.png') {
                $this->deleteFile($old_watermark_img);
                $this->deleteFile(str_replace('.', '1.', $old_watermark_img)); //同时删除对应缩略图
                $this->deleteFile(str_replace('.', '2.', $old_watermark_img));
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "修改失败" . $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 活动id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->detail($this->request->id, null, null);

        if (empty($res)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $pictureLiveWorksModel = new PictureLiveWorks();
        $works_number = $pictureLiveWorksModel->getWorksNumber($this->request->id, [1, 3]);
        if ($works_number) {
            return $this->returnApi(202, "此活动已有用户参与，不允许删除");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 撤销 和发布
     * @param id int 活动id
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
